﻿namespace GreenIsomer.Data.Entities.Transform {
	using System;
	using System.IO;
	using System.Collections.Generic;

	public class Converter {

		public static string ResolvePath(string baseDirectory, string path) {
			if(string.IsNullOrEmpty(path)) return path;

			if(path.StartsWith(".", StringComparison.Ordinal))
				path = Path.Combine(baseDirectory, path);
			return Path.GetFullPath(path);
		}

		private Settings settings;
		private string baseDirectory;

		public Converter(Settings settings) : this(settings, null) { }

		public Converter(Settings settings, string baseDirectory) {
			if(settings == null) throw new ArgumentNullException("settings");

			this.settings = settings;

			if(string.IsNullOrEmpty(baseDirectory)) 
				this.baseDirectory = Environment.CurrentDirectory;
			else
				this.baseDirectory = baseDirectory;
		}

		public virtual Settings Settings {
			get { return settings; }
		}

		public virtual string BaseDirectory {
			get { return baseDirectory; }
			set { baseDirectory = value; }
		}

		public TextWriter Output { get; set; }

		public void Convert() {

			Input input = settings.Input;
			if(input == null || string.IsNullOrEmpty(input.File)) 
				throw new InvalidOperationException("Input file not specified.");

			if(Output != null) {
				string path = ResolvePath(baseDirectory, input.File);
				Output.WriteLine("  Loading " + path);
			}

			input.Load(baseDirectory);

			foreach(Output output in settings.Output) {

				if(string.IsNullOrEmpty(output.File))
					throw new InvalidOperationException("Output file not specified.");

				if(Output != null) {
					string path = ResolvePath(baseDirectory, output.File);
					Output.WriteLine("  Saving " + path);
				}

				output.Convert(input, baseDirectory);
			}

		}

	}

}